package com.sc.nft.dao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.sc.nft.entity.UserCreatorInfo;
import com.sc.nft.entity.dto.AdminPageListDTO;
import com.sc.nft.entity.dto.AdminPhonePageDTO;
import com.sc.nft.entity.dto.HomeBrandIslandDTO;
import com.sc.nft.entity.vo.*;
import com.sc.nft.entity.vo.ecology.adminDaoPhoneVO;
import com.sc.nft.mapper.UserCreatorInfoMapper;
import com.sc.nft.pool.UserPool;
import com.sc.nft.sup.PageRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * (user_creator_info)数据DAO
 *
 * @author Sun
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-05-30 15:17:11
 */
@Slf4j
@Repository
public class UserCreatorInfoDao extends ServiceImpl<UserCreatorInfoMapper, UserCreatorInfo> {

    @Resource
    private RedisTemplate redisTemplate;

    public List<UserCreatorInfo> getUserCreator() {
        QueryWrapper<UserCreatorInfo> wrapper = new QueryWrapper<>();
        wrapper.select("id,dao_name as nick_name");
        wrapper.orderByDesc("id");
        return list(wrapper);
    }

    public Page<UserCreatorInfo> pageUserCreator(int pageNo, int pageSize, String nickName) {
        LambdaQueryWrapper<UserCreatorInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(nickName != null, UserCreatorInfo::getNickName, nickName);
        return page(new Page<>(pageNo, pageSize), wrapper);
    }

    public Boolean updateUserCreator(Long id, String nickName, String creatorPresentation, String creatorAvatarImg) {
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        userCreatorInfo.setId(id);
        userCreatorInfo.setNickName(nickName);
        userCreatorInfo.setCreatorPresentation(creatorPresentation);
        userCreatorInfo.setCreatorAvatarImg(creatorAvatarImg);
        return userCreatorInfo.updateById();
    }

    public Page<UserCreatorListVO> getUserCreatorList(int pageNo, int pageSize) {
        return baseMapper.getUserCreatorList(new Page(pageNo, pageSize));
    }

    public List<UserCreatorVO> getUserCreatorList() {
        QueryWrapper<UserCreatorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("show_search_status", 1);
        wrapper.select("id,dao_name as nick_name");
        List<UserCreatorInfo> list = list(wrapper);

        List<UserCreatorVO> UserCreatorList = list.stream().map(v -> {
            return new UserCreatorVO(v.getId(), v.getNickName());
        }).collect(Collectors.toList());

        UserCreatorList.add(new UserCreatorVO(0L, "全部作者"));
        return UserCreatorList;
    }

    public Page<GetUserApplyCreateDaoVO> getUserApplyCreateDaoVO(PageRequest pageRequest) {
        return baseMapper.getUserApplyCreateDaoVO(pageRequest.toMp(), UserPool.getUser().getId());
    }

    public Page<GetUserApplyCreateDaoVO> userJoinGroup(PageRequest pageRequest) {
        return baseMapper.userJoinGroup(pageRequest.toMp(), UserPool.getUser().getId());
    }

    public GetUserApplyCreateDaoVO getCertainlyShowData() {
        return baseMapper.getCertainlyShowData();
    }

    /**
     * 品牌岛
     *
     * @return
     */
    public List<HomeBrandIslandVO> homeBrandIsland() {
        return baseMapper.homeBrandIsland();
    }

    public Page<HomeBrandIslandVO> homeBrandIslandPage(HomeBrandIslandDTO result) {
        return baseMapper.homeBrandIslandPage(result.toMp(), result);
    }

    public GetDaoByIdVO getDaoById(Long id) {
        return baseMapper.getDaoById(id);
    }

    public List<UserCreatorInfo> getDaoByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    public GetDaoByIdVO getCertainlyShowDao() {
        return baseMapper.getCertainlyShowDao();
    }

    /**
     * 后台管理获取dao列表
     *
     * @param adminPageListDTO
     * @return
     */
    public Page<AdminUserCreatorInfoVO> getAdminPageList(AdminPageListDTO adminPageListDTO) {
        return baseMapper.getAdminPageList(adminPageListDTO.toMp(), adminPageListDTO.getName(), adminPageListDTO.getUserTel(), adminPageListDTO.getFilterMeta());
    }

    /**
     * 后台管理获取所有dao列表
     *
     * @return
     */
    public List<AdminUserCreatorInfoAllDao> getAll() {
        return baseMapper.getAll();
    }

    public List<UserCreatorInfo> listUserCreatorByPool() {
        LambdaQueryWrapper<UserCreatorInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCreatorInfo::getStatus, Boolean.TRUE);
        wrapper.eq(UserCreatorInfo::getEnableEcologyPool, Boolean.TRUE);
        wrapper.eq(UserCreatorInfo::getEnableJoinRank, Boolean.TRUE);
        return list(wrapper);
    }

    public AdminGetByIdVO adminGetById(Long id) {
        return baseMapper.adminGetById(id);
    }

    /**
     * 审核状态修改
     *
     * @param id
     * @param status
     * @return
     */
    public Boolean updateInfoStatus(Long id, Integer status) {
        UpdateWrapper<UserCreatorInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("info_status", status);
        return SqlHelper.retBool(baseMapper.update(new UserCreatorInfo(), updateWrapper));
    }

    public UserCreatorInfo getByIdCash(Long userCreatorId) {
        String key = StrUtil.format("UserCreatorInfo:getByIdCash:{}", userCreatorId);
        if (redisTemplate.hasKey(key)) {
            String data = (String) redisTemplate.opsForValue().get(key);
            return JSON.parseObject(data, UserCreatorInfo.class);
        }
        UserCreatorInfo userCreatorInfo = getById(userCreatorId);
        if (BeanUtil.isNotEmpty(userCreatorInfo)) {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(userCreatorInfo), 1, TimeUnit.HOURS);
        }
        return userCreatorInfo;
    }

    /**
     * 根据藏品id获取他下面在售的商品
     *
     * @param id
     * @return
     */
    public List<GetWhatHeSSellingUnderTheCollectionVO> getWhatHeSSellingUnderTheCollectionId(Long id) {
        return baseMapper.getWhatHeSSellingUnderTheCollectionId(id);
    }

    public Page<SimpleDaoPageVO> getSimpleDaoPage(String daoName, Integer pageNo, Integer pageSize) {
        return baseMapper.getSimpleDaoPage(new Page<>(pageNo, pageSize), daoName);
    }

    public Page<SimpleDaoPageVO> getSimpleOnlineTimeDaoPage(String daoName, Integer pageNo, Integer pageSize) {
        return baseMapper.getSimpleOnlineTimeDaoPage(new Page<>(pageNo, pageSize), daoName);
    }

    public List<UserCreatorInfo> getAllDaoList() {
        LambdaQueryWrapper<UserCreatorInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCreatorInfo::getStatus, 1);
        return list(wrapper);
    }

    /**
     * 获取用户所属的网体
     *
     * @param userId
     * @return
     */
    public Long theNetworkToWhichTheUserBelongs(Long userId) {
        return baseMapper.theNetworkToWhichTheUserBelongs(userId);
    }

    public List<UserCreatorInfo> getList() {
        return list();
    }

    public List<AdminUserCreatorInfoAllDao> getAllByStatus() {
        return baseMapper.getAllByStatus();
    }

    public IPage<UserCreatorVO> getAuthorList(PageRequest request) {
        QueryWrapper<UserCreatorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("show_search_status", 1);
        wrapper.select("id,dao_name as nick_name");
        Page<UserCreatorInfo> page = page(request.toMp(), wrapper);

        IPage<UserCreatorVO> convert = page.convert(v -> {
            return new UserCreatorVO(v.getId(), v.getNickName());
        });

        // 第一页给多返回一个全部作者其他的时候只分页 不返回.
        if (request.getPageNo() == 1) {
            convert.getRecords().add(0, new UserCreatorVO(0L, "全部作者"));
        }
        return convert;
    }

    /**
     * 修改dao的UUID
     *
     * @param daoId
     * @return
     */
    public Boolean updateDaoUUId(Long daoId) {
        LambdaUpdateWrapper<UserCreatorInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(UserCreatorInfo::getDaoUuid, IdUtil.simpleUUID());
        updateWrapper.eq(UserCreatorInfo::getId, daoId);
        return update(updateWrapper);
    }

    /**
     * 查询已加入排行榜的DAO列表
     *
     * @return UserCreatorInfo
     */
    public List<UserCreatorInfo> getEnableJoinRankDao() {
        LambdaQueryWrapper<UserCreatorInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserCreatorInfo::getStatus, Boolean.TRUE);
        queryWrapper.eq(UserCreatorInfo::getEnableJoinRank, Boolean.TRUE);
        queryWrapper.orderByDesc(UserCreatorInfo::getId);
        return list(queryWrapper);
    }

    /**
     * 查询已开启生态池的DAO列表
     *
     * @return UserCreatorInfo
     */
    public List<UserCreatorInfo> getEnableEcologyPools() {
        LambdaQueryWrapper<UserCreatorInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserCreatorInfo::getStatus, Boolean.TRUE);
        queryWrapper.eq(UserCreatorInfo::getEnableEcologyPool, Boolean.TRUE);
        queryWrapper.orderByDesc(UserCreatorInfo::getId);
        return list(queryWrapper);
    }

    public List<UserCreatorInfo> getListByUserId(Long userId) {
        LambdaQueryWrapper<UserCreatorInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserCreatorInfo::getUserId, userId);
        return list(queryWrapper);
    }

    /**
     * 根据DAO名称查询
     *
     * @param daoName
     * @return
     */
    public UserCreatorInfo getDaoByDaoName(String daoName) {
        LambdaQueryWrapper<UserCreatorInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserCreatorInfo::getStatus, 1);
        queryWrapper.eq(UserCreatorInfo::getDaoName, daoName);
        queryWrapper.last("limit 1");
        return baseMapper.selectOne(queryWrapper);
    }


    /**
     * 修改dao的手机号
     *
     * @param daoId
     * @param updateFrontTel
     * @param modifyId
     * @return
     */
    public Boolean updateDaoPhone(Long daoId, String updateFrontTel) {
        LambdaUpdateWrapper<UserCreatorInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(UserCreatorInfo::getPhoneNo, updateFrontTel);
        updateWrapper.eq(UserCreatorInfo::getId, daoId);
        return update(updateWrapper);

    }

    /**
     * 后台管理获取dao手机列表
     *
     * @param adminPhonePageDTO
     * @return
     */
    public Page<AdminUserCreatorInfoPhoneVO> getAdminPhonePage(AdminPhonePageDTO adminPhonePageDTO) {
        return baseMapper.getAdminPhonePage(adminPhonePageDTO.toMp(), adminPhonePageDTO.getName(), adminPhonePageDTO.getPhoneNo(), adminPhonePageDTO.getFilterMeta());
    }


    /**
     * 根据daoId 查询手机号
     *
     * @param id
     * @return
     */
    public adminDaoPhoneVO adminPhoneById(Integer id) {
        return baseMapper.adminPhoneById(id);
    }

    /**
     * 删除dao中手机号  赋null
     *
     * @param id
     * @return
     */
    public boolean updateDaoPhoneNoStatus(Long id) {
        LambdaUpdateWrapper<UserCreatorInfo> wrapper = new LambdaUpdateWrapper();
        wrapper.eq(UserCreatorInfo::getId, id);
        wrapper.set(UserCreatorInfo::getPhoneNo, null);
        return update(wrapper);
    }

    /**
     * 获取用户所属的网体
     *
     * @param userId
     * @return
     */
    public List<Long> getUserBelongingToDao(Long userId) {
        return baseMapper.getUserBelongingToDao(userId);
    }

    public Boolean updateShowEcologyStatus(Long id, Boolean showEcologyStatus) {
        LambdaUpdateWrapper<UserCreatorInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCreatorInfo::getId, id);
        updateWrapper.set(UserCreatorInfo::getShowEcologyStatus, showEcologyStatus);
        return update(updateWrapper);
    }

    /**
     * 更新是否展示销毁质押
     *
     * @param id
     * @param showPledgeStatus
     * @return
     */
    public Boolean updateShowPledgeStatus(Long id, Boolean showPledgeStatus) {
        LambdaUpdateWrapper<UserCreatorInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCreatorInfo::getId, id);
        updateWrapper.set(UserCreatorInfo::getShowPledgeStatus, showPledgeStatus);
        return update(updateWrapper);
    }

}